package com.example.xademo.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @describte:TODO
 * @program:xa-demo
 * @author:zhengdp
 * @create:2021-09-26 14:19:48
 **/
@Configuration
@MapperScan(value = "com.example.xademo.db132.dao",
        sqlSessionFactoryRef = "sqlSessionFactoryBean132")
public class ConfigDb132 {

    // 手动配置数据源
    @Bean("db132")
    public DataSource db131(){
        // 使用Mysql的XA数据源
        MysqlXADataSource xaDataSource = new MysqlXADataSource();
        xaDataSource.setUser("zdp");
        xaDataSource.setPassword("Log3.1415926");
        xaDataSource.setUrl("jdbc:mysql://192.168.0.133:3306/xa_132");

        // 使用Atomikos统一管理数据源
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(xaDataSource);
        atomikosDataSourceBean.setUniqueResourceName("xa_132");
        return atomikosDataSourceBean;
    }

    // 配置MyBatis的数据源
    @Bean("sqlSessionFactoryBean132")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("db132") DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("mybatis/db132/*.xml"));
        return sqlSessionFactoryBean;
    }
}
